package com.bluedot.filter;

import com.alibaba.fastjson.JSON;
import com.bluedot.dao.jedis.JedisUtil;
import com.bluedot.pojo.pack.ResultEntity;
import com.bluedot.utils.MessageUtil;
import redis.clients.jedis.Jedis;

import javax.mail.MessagingException;
import javax.servlet.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.UUID;

public class MessageFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        // 1.获得邮箱
        String email = request.getParameter("email");
        // 2.设置验证码
        String content = UUID.randomUUID().toString().replace("-"," ").substring(0,5);
        // 3.发送验证码
        try {
            MessageUtil.sendMessage(email,content);
            // 4.存放到Redis中
            Jedis jedis = new JedisUtil().getJedis();
            jedis.set(email,content);
            jedis.expire(email,60*5);
        } catch (MessagingException e) {
            // 5.写入响应包中
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().println(JSON.toJSONString(ResultEntity.falseWithoutData("发送失败")));
            response.getWriter().flush();
        }
        // 5.写入响应包中
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(JSON.toJSONString(ResultEntity.successWithoutData()));
        response.getWriter().flush();
    }
}
